<template>
  <header class="header">
    <div class="header-container">
      <!-- 左侧菜单按钮 -->
      <div class="menu-button" @click="drawerVisible = true">
        <el-icon size="24"><Menu /></el-icon>
      </div>
      
      <!-- 中间 Logo -->
      <router-link to="/" class="logo">
        <img src="/logo.png" alt="StoryPlush" />
        <span>StoryPlush</span>
      </router-link>
      
      <!-- 右侧用户操作区 -->
      <div class="header-right">
        <!-- 购物车 -->
        <div class="cart-icon" @click="goToCart">
          <el-badge :value="cartCount" :hidden="cartCount === 0">
            <el-icon size="24"><ShoppingCart /></el-icon>
          </el-badge>
        </div>
        
        <!-- 心愿单 -->
        <div class="wishlist-icon" @click="goToWishlist">
          <el-badge :value="wishlistCount" :hidden="wishlistCount === 0">
            <el-icon size="24"><Star /></el-icon>
          </el-badge>
        </div>
        
        <!-- 用户菜单 -->
        <el-dropdown v-if="isLoggedIn" trigger="click" @command="handleCommand">
          <div class="user-avatar">
            <el-avatar :size="32" :src="userAvatar">
              {{ userInfo.username?.charAt(0).toUpperCase() }}
            </el-avatar>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">个人中心</el-dropdown-item>
              <!-- <el-dropdown-item command="orders">我的订单</el-dropdown-item>
              <el-dropdown-item command="wishlist">心愿单</el-dropdown-item>
              <el-dropdown-item command="recent">最近浏览</el-dropdown-item>
              <el-dropdown-item command="address">收货地址</el-dropdown-item> -->
              <el-dropdown-item command="ai-chat">AI 助手</el-dropdown-item>
              <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        
        <!-- 未登录状态显示登录按钮 -->
        <router-link v-else to="/login" class="login-btn">
          <el-button type="primary">登录</el-button>
        </router-link>
      </div>
    </div>
    
    <!-- 侧边栏导航菜单 -->
    <el-drawer
      v-model="drawerVisible"
      title="导航菜单"
      direction="ltr"
      size="250px"
    >
      <el-menu
        :default-active="activeMenu"
        @select="handleMenuSelect"
      >
        <el-menu-item index="/">
          <el-icon><HomeFilled /></el-icon>
          <span>首页</span>
        </el-menu-item>
        <el-menu-item index="/new">
          <el-icon><Goods /></el-icon>
          <span>新品上市</span>
        </el-menu-item>
        <el-menu-item index="/hot">
          <el-icon><Star /></el-icon>
          <span>热门推荐</span>
        </el-menu-item>
        <el-menu-item index="/brand-story">
          <el-icon><Reading /></el-icon>
          <span>品牌故事</span>
        </el-menu-item>
        <el-menu-item index="/ai-chat">
          <el-icon><Service /></el-icon>
          <span>AI客服</span>
        </el-menu-item>
        
        <el-divider />
        
        <!-- <el-menu-item v-if="isLoggedIn" index="/profile">
          <el-icon><User /></el-icon>
          <span>个人中心</span>
        </el-menu-item>
        <el-menu-item v-if="isLoggedIn" index="/orders">
          <el-icon><List /></el-icon>
          <span>我的订单</span>
        </el-menu-item>
        <el-menu-item v-if="isLoggedIn" index="/wishlist">
          <el-icon><StarFilled /></el-icon>
          <span>心愿单</span>
        </el-menu-item>
        <el-menu-item v-if="isLoggedIn" index="/recent-views">
          <el-icon><View /></el-icon>
          <span>最近浏览</span>
        </el-menu-item>
        <el-menu-item v-if="isLoggedIn" index="/address">
          <el-icon><Location /></el-icon>
          <span>收货地址</span>
        </el-menu-item>
        
        <el-divider v-if="isLoggedIn" />
        
        <el-menu-item v-if="isLoggedIn" index="logout">
          <el-icon><SwitchButton /></el-icon>
          <span>退出登录</span>
        </el-menu-item> -->
        
        <!-- <el-menu-item v-else index="/login">
          <el-icon><Key /></el-icon>
          <span>登录/注册</span>
        </el-menu-item> -->
      </el-menu>
    </el-drawer>
  </header>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessageBox, ElMessage } from 'element-plus'
import { 
  Menu, 
  HomeFilled, 
  Goods, 
  Star, 
  StarFilled,
  Reading, 
  Service, 
  User, 
  List, 
  View, 
  Location, 
  SwitchButton, 
  Key,
  ShoppingCart 
} from '@element-plus/icons-vue'
import axios from '../utils/axios'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const cartCount = ref(0)
const wishlistCount = ref(0)
const drawerVisible = ref(false)

const isLoggedIn = computed(() => userStore.isLoggedIn)
const userInfo = computed(() => userStore.userInfo)
const activeMenu = computed(() => route.path)

const userAvatar = computed(() => {
  if (!userInfo.value.avatar) return '';
  
  if (userInfo.value.avatar.startsWith('http')) {
    return userInfo.value.avatar;
  }
  
  return `${import.meta.env.VITE_API_URL}/uploads/${userInfo.value.avatar}`;
})

const fetchCartCount = async () => {
  try {
    if (!isLoggedIn.value) {
      cartCount.value = 0;
      return;
    }
    
    const { data } = await axios.get('/api/cart/count');
    cartCount.value = data.count || 0;
  } catch (error) {
    console.error('Error fetching cart count:', error);
    cartCount.value = 0; // 出错时设置为0
  }
};

const refreshWishlist = async () => {
  if (!isLoggedIn.value) {
    wishlistCount.value = 0
    return
  }
  
  try {
    const { data } = await axios.get('/api/wishlist/count')
    wishlistCount.value = data.count
  } catch (error) {
    console.error('Error fetching wishlist count:', error)
  }
}

const refreshCounts = async () => {
  await Promise.all([fetchCartCount(), refreshWishlist()])
}

const goToCart = () => {
  try {
    router.push('/cart');
  } catch (error) {
    console.error('Error navigating to cart:', error);
    ElMessage.error('无法访问购物车，请稍后再试');
  }
}

const goToWishlist = () => {
  router.push('/wishlist')
}

const handleMenuSelect = (index) => {
  if (index === 'logout') {
    ElMessageBox.confirm(
      '确定要退出登录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      userStore.logout()
      router.push('/login')
    }).catch(() => {})
  } else {
    router.push(index)
  }
  drawerVisible.value = false
}

const handleCommand = (command) => {
  if (command === 'logout') {
    ElMessageBox.confirm(
      '确定要退出登录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      userStore.logout()
      router.push('/login')
    }).catch(() => {})
    return
  }
  
  const routes = {
    profile: '/profile',
    orders: '/orders',
    wishlist: '/wishlist',
    recent: '/recent-views',
    address: '/address',
    'ai-chat': '/ai-chat'
  }
  
  if (routes[command]) {
    router.push(routes[command])
  }
}

// 暴露方法给父组件
defineExpose({
  refreshCart: fetchCartCount,
  refreshWishlist,
  refreshCounts
})

onMounted(() => {
  refreshCounts()
})
</script>

<style scoped>
.header {
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.header-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.menu-button {
  cursor: pointer;
  padding: 8px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.menu-button:hover {
  background-color: #f5f7fa;
}

.logo {
  display: flex;
  align-items: center;
  font-size: 20px;
  font-weight: bold;
  color: #333;
  text-decoration: none;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.logo img {
  height: 36px;
  margin-right: 10px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.cart-icon,
.wishlist-icon {
  cursor: pointer;
  color: #333;
  transition: color 0.3s;
}

.cart-icon:hover,
.wishlist-icon:hover {
  color: var(--el-color-primary);
}

.user-avatar {
  cursor: pointer;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .logo {
    font-size: 18px;
  }
  
  .logo img {
    height: 30px;
  }
  
  .header-container {
    padding: 0 15px;
  }
  
  .header-right {
    gap: 15px;
  }
}

/* 小屏幕设备上隐藏品牌名称，只显示logo */
@media (max-width: 480px) {
  .logo span {
    display: none;
  }
  
  .logo img {
    margin-right: 0;
  }
}
</style> 